package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

const (
	ISSUE = "I28BNK"
	OWNER = "kesin"
	REPO  = "GiteeAutoUpdate"
	TOKEN = "xxxxxx" // Gitee 私人令牌
)

func main() {
	processArgs(os.Args)
}

func processArgs(args []string) {
	// no valid args
	if len(args) < 2 {
		usage()
	}

	// proceed by args
	switch args[1] {
	case "welcome":
		welcomeMsg(args[2])
	case "checkfile":
		checkFile(args[2])
	case "result":
		resultBack(args)
	case "-h":
		usage()
	default:
		usage()
	}
}

func usage() {
	fmt.Printf(`giteeCheck - used for open source project ci flow Jenkins script

Args:
	welcome ${giteePullRequestIid} add welcome message and some other message once PR created
	checkfile {filePath}
	result ${giteePullRequestIid} ${sonarResUrl} $buildStatus $buildStatus $syncFormat
	-h	Help and quit

`)
	os.Exit(0)
}

func welcomeMsg(PRIID string) {
	params := make(map[string]interface{})
	params["access_token"] = TOKEN

	if noteNotExist(PRIID) {
		// create first welcome note
		params["body"] = fmt.Sprintf(`欢迎提交 PR，您需要进行如下两步：
						 1. [点击此处阅读贡献者协议及注意事项](https://gitee.com/%s/%s/issues/%s)
						 2. 在本 PR 评论「Rebuild」继续执行构建集成测试状态，表示您阅读并同意了「贡献者协议」
						 `, OWNER, REPO, ISSUE)
		commentUrl := fmt.Sprintf("https://gitee.com/api/v5/repos/%s/%s/pulls/%s/comments", OWNER, REPO, PRIID)
		postForm(commentUrl, params)
		fmt.Printf("0")
		return
	}
	fmt.Printf("1")
}

func checkFile(file string) {
	projects := make(map[string][]string)
	jsonFile, err := os.Open(file)
	if err != nil {
		fmt.Printf("invalid")
		return
	}
	defer jsonFile.Close()

	jsonParser := json.NewDecoder(jsonFile)
	if err := jsonParser.Decode(&projects); err != nil {
		fmt.Printf("invalid")
		return
	}
	fmt.Printf("valid")
}

func resultBack(args []string) {
	var a, b, c, d = "success", "success", "success", "success"
	status := make(map[string]string)
	status["valid"] = ":white_check_mark:"
	status["invalid"] = ":x:"

	// sonar warningCount
	sonarRes, _ := http.Get(args[3])
	sonarResBody, _ := ioutil.ReadAll(sonarRes.Body)

	var sonarJson map[string]map[string]interface{}
	var sonarStatus string
	json.Unmarshal(sonarResBody, &sonarJson)
	if sonarJson["task"]["warningCount"].(float64) == 0 {
		sonarStatus = ":white_check_mark:"
		d = "No Warings"
	} else {
		sonarStatus = ":x:"
		d = fmt.Sprintf("Warings: %f", sonarJson["task"]["warningCount"].(float64))
	}

	// others
	if args[4] == "invalid" {
		a = "请本地构建成功后再行提交"
	}

	if args[5] == "invalid" {
		b = "有重复的提交"
	}

	if args[6] == "invalid" {
		c = "syncWhitelist 格式有误，请确认"
	}

	var botMsg string
	if a == "success" && b == "success" && c == "success" {
		botMsg = "所有检查通过，请 @Zoker 处理"
	} else {
		botMsg = "检测到有 **未通过项** ，请检查调整后重新提交，将会自动重新触发检查。"
	}

	params := make(map[string]interface{})
	params["access_token"] = TOKEN
	params["body"] = fmt.Sprintf(`自动化检测已完成，请根据结果进行调整：

| 步骤   |  结果  | 备注 |
|-------------|---|-----------------|
|      构建 |  %s  |     %s         |
|      提交信息检查    |  %s  |       %s       |
|      syncWhitelist 格式检查       |  %s |   %s      |
|      Sonar 质量检测       | %s  |         %s       |

%s
`, status[args[4]], a, status[args[5]], b, status[args[6]], c, sonarStatus, d, botMsg)

	commentUrl := fmt.Sprintf("https://gitee.com/api/v5/repos/%s/%s/pulls/%s/comments", OWNER, REPO, args[2])
	postForm(commentUrl, params)

}

func postForm(uri string, params map[string]interface{}) {
	data := ""
	for k, v := range params {
		data += fmt.Sprintf("%s=%s&%s", k, v.(string), data)
	}

	_, _ = http.Post(uri, "application/x-www-form-urlencoded", strings.NewReader(data))
}

func noteNotExist(PRIID string) bool {
	url := fmt.Sprintf("https://gitee.com/api/v5/repos/%s/%s/pulls/%s/comments?page=1&per_page=2", OWNER, REPO, PRIID)
	response, _ := http.Get(url)
	defer response.Body.Close()

	body, _ := ioutil.ReadAll(response.Body)

	var result []interface{}
	json.Unmarshal(body, &result)
	if len(result) == 0 {
		return true
	}
	return false
}
